<?php
declare (strict_types=1);

namespace app\common\middleware;

use Closure;
use think\Request;

/**
 * 跨域请求支持
 * Class AllowCrossDomain
 * @package cores\middleware
 */
class AllowCrossDomain
{
    /**
     * @notes 允许跨域
     * @param Request $request
     * @param Closure $next
     * @param array|null $header
     * @return mixed
     * @author mjf
     * @date 2022/4/1 18:40
     */
    public function handle(Request $request, Closure $next, ?array $header = [])
    {
        $header = !empty($header) ? array_merge($this->getHeader(), $header) : $this->getHeader();

        return $next($request)->header($header);
    }

    /**
     * @notes 获取header参数
     * @return array
     * @author mjf
     * @date 2022/4/1 18:41
     */
    private function getHeader()
    {
        $headers = array_merge([
            'Authorization', 'Content-Type', 'X-CSRF-TOKEN', 'X-Requested-With',
            'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Unmodified-Since'
        ], $this->getCustomHeader());

        return [
            // 允许所有域名访问
            'Access-Control-Allow-Origin' => '*',
            // 允许cookie跨域访问
            'Access-Control-Allow-Credentials' => 'true',
            // 预检请求的有效期
            'Access-Control-Max-Age' => 1800,
            // 允许跨域的方法
            'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
            // 跨域请求header头
            'Access-Control-Allow-Headers' => implode(',', $headers),
        ];
    }

    /**
     * @notes 获取允许跨域的header参数
     * @return string[]
     * @author mjf
     * @date 2022/4/1 18:41
     */
    private function getCustomHeader()
    {
        return [
            'Access-Token',
            'storeId',
            'platform',
        ];
    }
}
